package com.meiyou.controller;

import java.io.File;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.meiyou.pojo.EasyUIDataGrid;
import com.meiyou.pojo.GuideDetails;
import com.meiyou.pojo.MeiyouEvaluate;
import com.meiyou.pojo.MeiyouGuide;
import com.meiyou.pojo.MeiyouPtjls;
import com.meiyou.pojo.Meiyougbask;
import com.meiyou.pojo.vo.GuideVo;
import com.meiyou.service.AppSettingService;
import com.meiyou.service.EvaContentService;
import com.meiyou.service.GuideService;
import com.meiyou.service.PtjlsService;
import com.meiyou.service.UserService;
import com.meiyou.utils.Context;
import com.meiyou.utils.Msg;
import com.meiyou.utils.PagesMap;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Controller
@Api(value = "美游app控制器", tags = { "所有api接口" })
public class GuideController {
	@Resource
	private GuideService guideServiceImpl;
	@Resource
	private AppSettingService appsetting;
	@Resource
	private PtjlsService ptjlsServiceImpl;
	@Resource
	private UserService userServiceImpl;
	@Resource
	private EvaContentService evaContentServiceImpl;

	@RequestMapping(value = "insGuide", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "发布专职导游")
	public Msg insGuide(@RequestParam("mfile") MultipartFile[] mfile,String gArea,String gShuoming,Integer gMeijin,
			Integer gZdtime,HttpServletRequest request,double ZhiDingfei,String pay){
		if(request.getSession().getAttribute("user")==null) {
			System.out.println("session值位空");
			Msg.fail();
		}else {
		String uCount = request.getSession().getAttribute("user")+"";
		System.out.println("session值"+uCount);
		double meijin = Double.parseDouble(userServiceImpl.selUserByUcount(uCount));
		System.out.println(meijin);
		String num=appsetting.selFaBuJin();
		int fabujin=Integer.parseInt(num);
		System.out.println(fabujin);
		if(meijin>=fabujin+ZhiDingfei){
			String payword = userServiceImpl.selUserPayByUcount(uCount);
			System.out.println(payword);
			if(pay!=null&&pay.equals(payword)){
				//这里mfile可以接受前台的文件，可以是一个，也可以是多个，这正是MultipartFile强大的地方。
				HashMap<String, String> map=new HashMap<String, String>();
				//建一个Map便于返回json
				String filePath =null;
				String fileName[]=new String[mfile.length];
				Date date=new Date();
				//根据传递文件个数返回文件（{msg1:"sss.png",msg2:"aa.jpg"}
				String img = "[";
				if (mfile != null && mfile.length > 0) {
				//判断使用有文件上传
					for (int i = 0; i < mfile.length; i++) {
						//循环上传（多文件上传）
						try {
							Calendar cale = null;	
							cale = Calendar.getInstance();
							int year = cale.get(Calendar.YEAR);
							int month = cale.get(Calendar.MONTH) + 1;
							int day = cale.get(Calendar.DATE);
							String address = Context.fwqaddress;
							//给图片重命名加上日期前缀
							filePath= request.getSession().getServletContext().getRealPath("/") ;
							//获取服务器img文件夹地址（这里指的是local:8080/项目名/img）
							fileName[i]= "/imgs/" + year + ""+ month + "" + day + "_" + mfile[i].getOriginalFilename();
							//重命名图片。
							String type = fileName[i].substring(fileName[i].lastIndexOf(".")+1, fileName[i].length());
							//截取文件后缀判断是否是一张图片
							if((type.equals("png"))||(type.equals("jpg"))||(type.equals("jpeg"))){
								int length = mfile[i].getBytes().length;
								if (!((length / 1000) > 5120)) {
									//判断图片地址
									map.put("msg"+i, fileName[i]);
									//将图片输出到制定的文件夹目录中
									mfile[i].transferTo(new File(filePath,fileName[i]));
									if(i==mfile.length-1){
										img +="\""+address+fileName[i]+"\"]";
									}else{
										img +="\""+address+fileName[i]+"\",";
									}
									
								}else{
									map.put("msg", "图片过大");
								}}else{
								map.put("msg", "只能上传图片啊亲!");}
						} catch (Exception e) {
							e.printStackTrace();
							map.put("msg", "上传失败");}}} else {
					map.put("msg", "请选择文件");}
				MeiyouGuide meiyouGuide = new MeiyouGuide();
				meiyouGuide.setgTime(date);
				meiyouGuide.setgState("已发布");
				meiyouGuide.setgUCount(uCount);
				meiyouGuide.setgArea(gArea);
				meiyouGuide.setgImg(img);
				meiyouGuide.setgShuoming(gShuoming);
				meiyouGuide.setgMeijin(gMeijin);
				meiyouGuide.setgZdtime(gZdtime);
				int index=guideServiceImpl.insGuide(meiyouGuide);
				if(index>0){
					MeiyouPtjls meiyouPtjls=new MeiyouPtjls();
					meiyouPtjls.setpMeijin(fabujin);
					meiyouPtjls.setpTime(date);
					meiyouPtjls.setpUCount(uCount);
					int ptjls = ptjlsServiceImpl.insPtjls(meiyouPtjls);
					double uMeijin=meijin-(ZhiDingfei+fabujin);
					int upd = userServiceImpl.updUserMeijin(uMeijin,uCount);
					if(ptjls>0 && upd>0){
						return Msg.success();
					}
				}
			}else {
				return Msg.fail();
			}
		}else{
			return Msg.fail();
		}
		}
		return Msg.success();
	}
	@RequestMapping(value = "hireGuide", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "聘请导游")
	public Msg hireGuide(String uCount,String pay,int gId,int time){
		double meijin = Double.parseDouble(userServiceImpl.selUserByUcount(uCount));
		String payword = userServiceImpl.selUserPayByUcount(uCount);
		int gMeijin = guideServiceImpl.selMeijin(gId);
		if(payword!=null&&!payword.equals("")&&payword.equals(pay)){
			int Apply=10;
			if(meijin>=Apply+gMeijin*time){
			double uMeijin=meijin-Apply-gMeijin*time;
			int upd = userServiceImpl.updUserMeijin(uMeijin, uCount);
			Date date = new Date();
			MeiyouPtjls meiyouPtjls=new MeiyouPtjls();
			meiyouPtjls.setpMeijin(Apply);
			meiyouPtjls.setpTime(date);
			meiyouPtjls.setpUCount(uCount);
			int ptjls = ptjlsServiceImpl.insPtjls(meiyouPtjls);
			if(ptjls>0&&upd>0){
				Meiyougbask meiyougbask = new Meiyougbask();
				meiyougbask.setgGId(gId);
				meiyougbask.setgState("聘请成功");
				meiyougbask.setgTime(date);
				meiyougbask.setgUCount(uCount);
				int index = guideServiceImpl.insGbask(meiyougbask);
				if(index>0){
				    return Msg.success();
				}else {
					return Msg.fail();
				}
			}
			}
		}
		else{
			return Msg.fail();
		}
		return Msg.fail();
	}

	@RequestMapping(value = "selAllGuide", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "显示所有导游信息")
	public List<GuideVo> selAllGuide(HttpServletRequest request) {
		String gUcount = request.getSession().getAttribute("user")+"";
		return guideServiceImpl.selAllGuide(gUcount);
	}
	
	@RequestMapping(value = "selAllGuideTerm", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "条件查询导游信息")
	public List<GuideVo> selAllGuideTerm(String uSex,HttpServletRequest request) {
		String gUcount = request.getSession().getAttribute("user")+"";
		return guideServiceImpl.selAllGuideTerm(gUcount,uSex);
	}
	
	@RequestMapping(value = "selAllGuideDetails", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "显示导游详情")
	public GuideDetails selAllGuideDetails(int gId) {
		GuideDetails selGuideDetails = guideServiceImpl.selGuideDetails(gId);
		JSONArray array = JSONArray.parseArray(selGuideDetails.getG_img());
		selGuideDetails.setArray(array);
		return selGuideDetails;
	}
	
	@RequestMapping(value = "delGuide", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "删除个人导游信息")
	public int delMyGuide(int gId){
		return guideServiceImpl.delGuide(gId);
	}
	
	@RequestMapping(value = "showGuide", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "后台显示导游信息")
	public Msg showGuide(int pn,MeiyouGuide meiyouGuide){
		List<MeiyouGuide> list = guideServiceImpl.showGuide(meiyouGuide);
		Map<String, Object> map = PagesMap.getpagesGuideMaps(list, pn);
		return Msg.success().add("pageInfo", map);
	}
	
	@RequestMapping(value = "selAll", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "后台模糊查询导游信息")
	public EasyUIDataGrid selAll(String gUCount,int rows,int page){
		return guideServiceImpl.selgUCount(gUCount, rows, page);
	}
	
	@RequestMapping(value = "gdPingxing", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "导游评星")
	public Msg gdPingxing(int gAssess,int gId,String eUBcount,HttpServletRequest request){
		String eUCount = request.getSession().getAttribute("user")+"";
		Date date = new Date();
		MeiyouEvaluate meiyouEvaluate = new MeiyouEvaluate();
		int assess = guideServiceImpl.selGuideAssess(gId);
		if(assess==0){
			guideServiceImpl.updGuideAssess(gAssess, gId);
			meiyouEvaluate.setContent(Integer.toString(gAssess));
			meiyouEvaluate.seteUBcount(eUBcount);
			meiyouEvaluate.setTime(date);
			meiyouEvaluate.seteUCount(eUCount);
			meiyouEvaluate.setgId(gId);
			evaContentServiceImpl.insEvaluate(meiyouEvaluate);
			return Msg.success();
		}else {
			gAssess=(assess+gAssess)/2;
			guideServiceImpl.updGuideAssess(gAssess, gId);
			meiyouEvaluate.setContent(Integer.toString(gAssess));
			meiyouEvaluate.seteUCount(eUCount);
			meiyouEvaluate.setTime(date);
			meiyouEvaluate.seteUBcount(eUBcount);
			meiyouEvaluate.setgId(gId);
			evaContentServiceImpl.insEvaluate(meiyouEvaluate);
			return Msg.success();
		}
			
		
		
	}
}
